import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { changeCreate, getVersionAsync } from "@/store/version/versionSlice";
import { DatePicker, Form, Input, Modal, Select, Upload } from "antd";
import { ReactElement, useEffect, useState } from "react";
import { shallowEqual } from "react-redux";
import dayjs from "@/utils/dayjs";
import { TZ } from "@/utils/env";
import { PlusOutlined } from "@ant-design/icons";
import { createVersion, updateVersion } from "@/store/version/versionAPI";

export default function Create(): ReactElement<typeof Modal, "div"> {
  const [loading, setLoading] = useState<boolean>(false);
  const { create, params } = useAppSelector(
    (state) => state.version,
    shallowEqual
  );
  const {
    config: {
      data: { data: { user_channel_list = [], version_path_type } = {} } = {},
    } = {},
  } = useAppSelector((state) => state.app, shallowEqual);
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  const handleClose = () => {
    dispatch(changeCreate({ open: false }));
    form.resetFields();
  };
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const p = new FormData();
      p.append("channel", values.channel);
      p.append("version", values.version);
      p.append("upload_type", values.upload_type);
      p.append("release_time", values.release_time.unix());
      if (values?.package?.[0]?.originFileObj) {
        p.append("package", values.package[0].originFileObj);
      }
      if(values?.download_path){
        p.append("download_path", values.download_path);
      }
      if (create.type === "create") {
        createVersion(p)
          .then(() => {
            handleClose();
            dispatch(getVersionAsync({ ...params }));
          })
          .finally(() => setLoading(false));
      } else if (create.type === "update") {
        p.append("version_id", String(create.record?.id));
        updateVersion(p)
          .then(() => {
            handleClose();
            dispatch(getVersionAsync({ ...params }));
          })
          .finally(() => setLoading(false));
      }
    } catch (err) {
      console.error("校验不通过");
    }
  };

  useEffect(() => {
    if (create.type === 'update' && create.open) {
      form.setFieldsValue(create.record)
      form.setFieldValue('channel', create.record?.channel_val)
      form.setFieldValue('release_time', dayjs.unix(create.record?.release_time as number).tz(TZ))
      form.setFieldValue('package', [
        {
          uid: "-1",
          name: create.record?.download_path,
          status: "done",
          url: create.record?.download_path,
        },
      ])
    }
  }, [create])

  const uploadTypeValue = Form.useWatch("upload_type", form)

  return (
    <Modal
      title={create.type === "create" ? "创建" : "编辑"}
      open={create.open}
      onCancel={handleClose}
      onOk={handleOk}
      confirmLoading={loading}
    >
      <Form
        form={form}
        initialValues={{
          release_time: dayjs().tz(TZ),
        }}
      >
        <Form.Item
          name="channel"
          label="渠道"
          rules={[{ required: true, message: "必填" }]}
        >
          <Select options={user_channel_list} />
        </Form.Item>
        <Form.Item
          name="version"
          label="版本号"
          rules={[{ required: true, message: "必填" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="upload_type"
          label="上传类型"
          rules={[{ required: true, message: "必填" }]}
        >
          <Select options={version_path_type} />
        </Form.Item>
        <Form.Item
          name="release_time"
          label="发布时间"
          rules={[{ required: true, message: "必填" }]}
        >
          <DatePicker showTime />
        </Form.Item>
        {
          uploadTypeValue === 1 && <Form.Item
            label="包"
            name="package"
            rules={[{ required: true, message: "必填" }]}
            valuePropName="fileList"
            getValueFromEvent={(e) => (Array.isArray(e) ? e : e?.fileList)}
          >
            <Upload.Dragger beforeUpload={() => false} maxCount={1}>
              <button style={{ border: 0, background: "none" }} type="button">
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>拖拽 或 选择</div>
              </button>
            </Upload.Dragger>
          </Form.Item>
        }
        {
          uploadTypeValue === 2 && <Form.Item
            name="download_path"
            label="下载地址"
            rules={[{ required: true, message: "必填" }]}
          >
            <Input />
          </Form.Item>
        }
      </Form>
    </Modal>
  );
}
